// src/stores/iam/IamRoleStore.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
import request from '@/utils/request'
import type { Role, RoleCreation, RoleUpdate } from '@/types/iam/IamRole'

// 模拟数据
const mockRoles: Role[] = [
  {
    role_id: 1,
    role_code: 'ADMIN',
    role_name: '系统管理员',
    description: '拥有系统所有权限的超级管理员',
    is_active: true,
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    role_id: 2,
    role_code: 'FINANCE_MANAGER',
    role_name: '财务经理',
    description: '负责财务管理相关功能的权限',
    is_active: true,
    created_at: '2023-02-20T09:15:00Z',
    updated_at: '2023-11-05T11:30:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    role_id: 3,
    role_code: 'PRODUCTION_MANAGER',
    role_name: '生产经理',
    description: '负责生产管理相关功能的权限',
    is_active: true,
    created_at: '2023-03-05T10:40:00Z',
    updated_at: '2023-11-15T15:10:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    role_id: 4,
    role_code: 'WAREHOUSE_MANAGER',
    role_name: '仓库经理',
    description: '负责仓库管理相关功能的权限',
    is_active: true,
    created_at: '2023-04-10T13:25:00Z',
    updated_at: '2023-11-18T10:50:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    role_id: 5,
    role_code: 'SALES_MANAGER',
    role_name: '销售经理',
    description: '负责销售管理相关功能的权限',
    is_active: false,
    created_at: '2023-05-15T11:10:00Z',
    updated_at: '2023-11-16T16:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  }
]

export const useIamRoleStore = defineStore('iamRole', () => {
  // 初始化时使用模拟数据
  const roleList = ref<Role[]>(mockRoles)
  const currentRole = ref<Role | null>(null)
  // 导出mockRoles以便在组件中直接访问
  const mockRolesRef = ref<Role[]>(mockRoles)

  const isEditing = ref(false)

  // 获取角色列表
  const fetchRoleList = async (signal?: AbortSignal) => {
    try {
      const response = await request.get('/api/iam/roles', { signal })

      // 添加类型检查，确保返回的是数组类型
      if (response && Array.isArray(response.data)) {
        roleList.value = response.data
      } else {
        // 如果不是数组类型，使用模拟数据并打印警告
        console.warn('获取的角色列表数据类型不正确，期望数组但得到:', typeof response.data)
        // 检查是否是HTML字符串
        if (response && typeof response.data === 'string' && (response.data as string).includes('<!DOCTYPE html>')) {
          console.error('API返回了HTML文档而不是JSON数据，这可能是因为后端接口未正确配置或存在CORS问题')
        }
        // 使用模拟数据代替
        roleList.value = [...mockRoles]
      }
    } catch (error) {
      // 如果接口调用失败，继续使用模拟数据
      if ((error as Error).name !== 'AbortError') {
        console.warn('获取角色列表失败，使用模拟数据:', error)
        // 使用模拟数据
        roleList.value = [...mockRoles]
      }
    }
  }

  // 新增角色
  const addRole = async (role: RoleCreation, signal?: AbortSignal) => {
    try {
      const response = await request.post('/api/iam/roles', role, { signal })

      // 添加类型检查
      if (response && response.data) {
        roleList.value.push(response.data)
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('新增角色失败:', error)
        // 模拟添加成功
        const newRole: Role = {
          ...role as Role,
          role_id: Date.now(), // 使用时间戳作为临时ID
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          is_deleted: false
        }
        roleList.value.push(newRole)
        console.log('已添加模拟角色')
      }
    }
  }

  // 编辑角色
  const updateRole = async (id: number, role: RoleUpdate, signal?: AbortSignal) => {
    try {
      const response = await request.put(`/api/iam/roles/${id}`, role, { signal })

      // 添加类型检查
      if (response && response.data) {
        const index = roleList.value.findIndex((r) => r.role_id === id)
        if (index !== -1) {
          roleList.value[index] = { ...roleList.value[index], ...response.data }
        }
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('编辑角色失败:', error)
        // 模拟编辑成功
        const index = roleList.value.findIndex((r) => r.role_id === id)
        if (index !== -1) {
          roleList.value[index] = {
            ...roleList.value[index],
            ...role,
            updated_at: new Date().toISOString()
          }
        }
        console.log('已更新模拟角色')
      }
    }
  }

  // 删除角色
  const deleteRole = async (id: number, signal?: AbortSignal) => {
    try {
      await request.delete(`/api/iam/roles/${id}`, { signal })
      roleList.value = roleList.value.filter((r) => r.role_id !== id)
    } catch (error) {
      // 使用类型断言将 error 转换为 Error 类型
      if ((error as Error).name !== 'AbortError') {
        console.error('删除角色失败:', error)
        // 模拟删除成功
        roleList.value = roleList.value.filter((r) => r.role_id !== id)
        console.log('已删除模拟角色')
      }
    }
  }

  // 设置当前编辑角色
  const setCurrentRole = (role: Role | null) => {
    currentRole.value = role
    isEditing.value = !!role
  }

  return {
    roleList,
    currentRole,
    mockRoles: mockRolesRef,
    isEditing,
    fetchRoleList,
    addRole,
    updateRole,
    deleteRole,
    setCurrentRole,
  }
})